import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:get/get.dart';
import 'package:shop/tools/keepAliveWrapper.dart';
import 'package:shop/tools/screenAdapter.dart';

import '../../../../tools/httpsClient.dart';
import '../../../../tools/iyyingFonts.dart';
import '../../../routes/app_pages.dart';
import '../controllers/home_controller.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({super.key});

  // 顶部栏
  Widget _homeBar() {
    return Positioned(
      left: 0,
      right: 0,
      top: 0,
      child: Obx(() {
        return AppBar(
          leading: controller.flag.value
              ? const Text('') // 增加 const 优化性能
              : Icon(ItYingFonts.xiaomi, color: Colors.white),
          leadingWidth: controller.flag.value
              ? ScreenAdapter.width(40)
              : ScreenAdapter.width(120),
          title: InkWell(
            onTap: () {
              Get.toNamed(Routes.SEARCH);
            },
            child: AnimatedContainer(
              width: controller.flag.value
                  ? ScreenAdapter.width(1000)
                  : ScreenAdapter.width(620),
              height: ScreenAdapter.height(96),
              decoration: BoxDecoration(
                color: const Color.fromARGB(237, 245, 237, 237),
                borderRadius: BorderRadius.circular(30),
              ),
              duration: const Duration(milliseconds: 1000),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Padding(
                    padding: EdgeInsets.fromLTRB(
                      ScreenAdapter.width(34),
                      0,
                      ScreenAdapter.width(10),
                      0,
                    ),
                    child: const Icon(Icons.search), // 增加 const 优化性能
                  ),
                  Text(
                    '手机',
                    style: TextStyle(fontSize: ScreenAdapter.fontSize(32)),
                  ),
                ],
              ),
            ),
          ),
          centerTitle: true,
          backgroundColor: controller.flag.value
              ? Colors.white
              : Colors.transparent,
          elevation: 0,
          // 消除阴影
          actions: [
            IconButton(
              onPressed: () {},
              icon: Icon(
                Icons.qr_code,
                color: controller.flag.value ? Colors.black : Colors.white,
              ),
            ),
            IconButton(
              onPressed: () {},
              icon: Icon(
                Icons.message,
                color: controller.flag.value ? Colors.black : Colors.white,
              ),
            ),
          ],
        );
      }),
    );
  }

  // 内容区域
  Widget _homePage() {
    return Positioned(
      top: -ScreenAdapter.height(90),
      left: 0,
      bottom: 0,
      right: 0,
      child: ListView(
        controller: controller.scrollController,
        children: [
          _focus(),
          _Banner(),
          _category(),
          _Banner2(),
          _bestSelling(),
          _waterFlowGoods(),
        ],
      ),
    );
  }

  // 官方商城Banner图片
  Widget _Banner() {
    return SizedBox(
      width: ScreenAdapter.width(1080),
      height: ScreenAdapter.height(92),
      child: Image.asset('assets/images/xiaomiBanner.png', fit: BoxFit.cover),
    );
  }

  // 滑动分类
  Widget _category() {
    return Container(
      width: ScreenAdapter.width(1080),
      height: ScreenAdapter.height(470),
      // color: Colors.red,
      child: Swiper(
        autoplay: true,
        itemBuilder: (context, index) {
          return GridView.builder(
            itemCount: 10,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 5,
              crossAxisSpacing: ScreenAdapter.width(20),
              mainAxisSpacing: ScreenAdapter.height(20),
            ),
            itemBuilder: (context, i) {
              return Column(
                children: [
                  Container(
                    alignment: Alignment.center,
                    width: ScreenAdapter.width(136),
                    height: ScreenAdapter.height(136),
                    child: Image.network(
                      HttpsClient.photoUrl(
                        controller.categoryList[index * 10 + i].pic,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(
                      0,
                      ScreenAdapter.height(4),
                      0,
                      0,
                    ),
                    child: Text(
                      '${controller.categoryList[index * 10 + i].title}',
                      style: TextStyle(fontSize: ScreenAdapter.fontSize(34)),
                    ),
                  ),
                ],
              );
            },
          );
        },
        itemCount: 2,
        pagination: SwiperPagination(
          margin: const EdgeInsets.all(0.0),
          builder: SwiperPagination(
            margin: const EdgeInsets.all(0.0),
            builder: SwiperCustomPagination(
              builder: (BuildContext context, SwiperPluginConfig config) {
                return ConstrainedBox(
                  constraints: BoxConstraints.expand(
                    height: ScreenAdapter.height(20),
                  ),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Align(
                          alignment: Alignment.center,
                          child: const RectSwiperPaginationBuilder(
                            color: Colors.black12,
                            activeColor: Colors.black54,
                          ).build(context, config),
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  // 官方商城Banner图片
  Widget _Banner2() {
    return Padding(
      padding: EdgeInsets.fromLTRB(
        ScreenAdapter.width(20),
        0,
        ScreenAdapter.height(20),
        0,
      ),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          image: DecorationImage(
            fit: BoxFit.cover,
            image: AssetImage('assets/images/xiaomiBanner2.png'),
          ),
        ),
        height: ScreenAdapter.height(420),
      ),
    );
  }

  // 热销臻选
  Widget _bestSelling() {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.fromLTRB(
            ScreenAdapter.width(30),
            ScreenAdapter.height(40),
            ScreenAdapter.width(30),
            ScreenAdapter.height(40),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                '热销臻选',
                style: TextStyle(
                  fontSize: ScreenAdapter.fontSize(46),
                  fontWeight: FontWeight.w600,
                ),
              ),
              Text(
                '更多手机推荐 >',
                style: TextStyle(fontSize: ScreenAdapter.fontSize(36)),
              ),
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(
            ScreenAdapter.width(30),
            ScreenAdapter.height(20),
            ScreenAdapter.width(30),
            ScreenAdapter.height(20),
          ),
          child: Row(
            children: [
              // 左侧
              Expanded(
                flex: 1,
                child: SizedBox(
                  height: ScreenAdapter.height(738),
                  child: Obx(() {
                    return Swiper(
                      itemCount: controller.bestSellingList.length,
                      itemBuilder: (context, index) {
                        return Image.network(
                          HttpsClient.photoUrl(
                            controller.bestSellingList[index].pic,
                          ),
                          fit: BoxFit.cover,
                        );
                      },
                      // control: const SwiperControl(),
                      pagination: const SwiperPagination(
                        builder: SwiperPagination.rect,
                      ),
                      autoplay: true,
                      // duration: 3000,
                    );
                  }),
                ),
              ),
              SizedBox(width: ScreenAdapter.width(20)),
              //  右侧
              Expanded(
                flex: 1,
                child: Container(
                  height: ScreenAdapter.height(738),
                  child: Obx(() {
                    return Column(
                      children: controller.pList.asMap().entries.map((entrie) {
                        var value = entrie.value;

                        return Expanded(
                          flex: 1,
                          child: Container(
                            margin: EdgeInsets.fromLTRB(
                              0,
                              0,
                              0,
                              entrie.key == 2 ? 0 : ScreenAdapter.height(20),
                            ),
                            color: const Color.fromRGBO(246, 246, 246, 1),
                            child: Row(
                              children: [
                                // 左侧
                                Expanded(
                                  flex: 3,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(
                                        '${value.title}',
                                        style: TextStyle(
                                          fontSize: ScreenAdapter.fontSize(38),
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      SizedBox(
                                        height: ScreenAdapter.height(10),
                                      ),
                                      Text(
                                        '${value.subTitle}',
                                        style: TextStyle(
                                          fontSize: ScreenAdapter.fontSize(28),
                                        ),
                                      ),
                                      SizedBox(
                                        height: ScreenAdapter.height(10),
                                      ),

                                      Text(
                                        '${value.price}元',
                                        style: TextStyle(
                                          fontSize: ScreenAdapter.fontSize(34),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                //   右侧
                                Expanded(
                                  flex: 2,
                                  child: Padding(
                                    padding: EdgeInsets.all(
                                      ScreenAdapter.width(10),
                                    ),
                                    child: Image.network(
                                      HttpsClient.photoUrl(value.pic),
                                      fit: BoxFit.fill,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      }).toList(),
                    );
                  }),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 商品瀑布流
  Widget _waterFlowGoods() {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.fromLTRB(
            ScreenAdapter.width(30),
            ScreenAdapter.height(40),
            ScreenAdapter.width(30),
            ScreenAdapter.height(40),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                '省心优惠',
                style: TextStyle(
                  fontSize: ScreenAdapter.fontSize(46),
                  fontWeight: FontWeight.w600,
                ),
              ),
              Text(
                '全部优惠 >',
                style: TextStyle(fontSize: ScreenAdapter.fontSize(36)),
              ),
            ],
          ),
        ),
        Obx(() {
          return Container(
            padding: EdgeInsets.all(ScreenAdapter.width(26)),
            color: const Color.fromRGBO(246, 246, 246, 1),
            child: MasonryGridView.count(
              crossAxisCount: 2,
              mainAxisSpacing: ScreenAdapter.width(26),
              crossAxisSpacing: ScreenAdapter.width(26),
              itemCount: controller.waterFlowList.length,
              shrinkWrap: true,
              //收缩，让元素宽度自适应
              physics: const NeverScrollableScrollPhysics(),
              //禁止左右滑动
              itemBuilder: (context, index) {
                return InkWell(
                  onTap: () {
                    Get.toNamed(
                      Routes.PRODUCT_CONTENT,
                      arguments: {"id": controller.waterFlowList[index].sId},
                    );
                  },
                  child: Container(
                    padding: EdgeInsets.all(ScreenAdapter.width(20)),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      color: Colors.white,
                    ),
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.all(ScreenAdapter.width(10)),
                          child: Image.network(
                            HttpsClient.photoUrl(
                              controller.waterFlowList[index].pic,
                            ),
                            fit: BoxFit.cover,
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.all(ScreenAdapter.width(10)),
                          width: double.infinity,
                          child: Text(
                            textAlign: TextAlign.start,
                            '${controller.waterFlowList[index].title}',
                            style: TextStyle(
                              fontSize: ScreenAdapter.fontSize(42),
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.all(ScreenAdapter.width(10)),
                          width: double.infinity,

                          child: Text(
                            textAlign: TextAlign.start,
                            '${controller.waterFlowList[index].subTitle}',
                            style: TextStyle(
                              fontSize: ScreenAdapter.fontSize(36),
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.all(ScreenAdapter.width(10)),
                          width: double.infinity,
                          child: Text(
                            textAlign: TextAlign.start,
                            '￥${controller.waterFlowList[index].price}元',
                            style: TextStyle(
                              fontSize: ScreenAdapter.fontSize(36),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          );
        }),
      ],
    );
  }

  // 轮播图代码
  Widget _focus() {
    return SizedBox(
      width: ScreenAdapter.width(1080),
      height: ScreenAdapter.height(682),
      child: Obx(() {
        return Swiper(
          itemCount: controller.swiperList.value.length,
          itemBuilder: (context, index) {
            return Image.network(
              HttpsClient.photoUrl(controller.swiperList[index].pic),
              fit: BoxFit.cover,
            );
          },
          // control: const SwiperControl(),
          pagination: const SwiperPagination(builder: SwiperPagination.rect),
          autoplay: true,
          // duration: 3000,
        );
      }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return KeepAliveWrapper(
      child: Scaffold(
        body: Stack(
          children: [
            // 第一个 Positioned：列表组件（原代码多了不必要的闭合大括号，已删除）
            _homePage(),
            // 第二个 Positioned：顶部 AppBar 区域（原代码嵌套错误，已调整层级）
            _homeBar(),
          ], // Stack 的 children 列表闭合
        ), // Stack 组件闭合
      ), // Scaffold 组件闭合
    ); // KeepAliveWrapper 组件闭合
  }
}
